import amara

from myelin.Ns import MYELINS, XML_NS
from myelin.server.core.ft import ModelDriver

from nodetypes.formats.Document import Document
from nodetypes import config

import Account


class Document(Document):
      
    method = 'mml'
    imt = config.METHODS_TO_IMT['mml']
    
    newAgentAccount = Account.AgentAccount
    newGuestAccount = Account.GuestAccount
    
    newContentDbDriver = staticmethod(ModelDriver.FromRepo)
    
    newNodeDocument = staticmethod(amara.create_document)
    
    def getLocale(self, context):
        for locale in context.model.dcLanguage:
            return locale.rdf_value
        else:
            return context.defaults.default_locale
        
    
    def createDocument(self, context, source):
        
        doc = self.startDocument(context, source)
        node = doc.childNodes[0]
        
        locale = self.getLocale(context)
        node.xml_set_attribute(u'content-locale',locale)
        
        #driver = reduce(lambda a,b:a+b,context.request.graphs.values(),[])
        #if driver:
        #    model = context.model
        #    context.contentDbDriver = model.rdf_initDriver(
        #        self.newContentDbDriver(
        #            context.repo,
        #            driver
        #        )
        #    )
        #else:
        #    context.contentDbDriver = context.dbDriver
        
        self.createBody(
            context,
            node,
            locale
        )
        
        return doc, self.imt
    
    def getNodeDocId(self, context):
        return
    
    def startDocument(self, context, source):
        action = context.action
        nodeType = context.nodeType
        actionType = nodeType.actions[action]
        typeInfo = nodeType.typeInfo
        
        attributes={
            u'node-id'         : context.sourceId,
            u'resource-uri'     : context.resourceUri,
            u'resource-type'    : context.classType,
            u'service-type'     : actionType.classTypes[0],
            u'service-handler'  : self.newServiceHandlerUri(
                action,                    
                typeInfo['name'],
                typeInfo['namespace-uri']
            ),
            u'action'           : action,
            u'method'           : context.method,
            u'document-id'      : self.newUri(),
            u'domain-uri'       : context.defaults.domain_uri,
            u'date-time'        : self.newDateTimeString(
                context.session.dateTime
            ),
        }
        doc = self.getNodeDocId(context)
        if doc:
            attributes[u'node-docid'] = doc
            
        ep = getattr(context.defaults,'sparql_endpoint',None)
        if ep:
            attributes[u'sparql-endpoint'] = context.urlFormatter.formatUrl(ep,method=context.method)
        ep = getattr(context.defaults,'versa_endpoint',None)
        if ep:
            attributes[u'versa-endpoint'] = context.urlFormatter.formatUrl(ep,method=context.method)
            
        ep = getattr(context.defaults,'keyword_search_endpoint',None)
        if ep:
            attributes[u'keyword-search-endpoint'] = context.urlFormatter.formatUrl(ep,method=context.method)
            
        doc = self.newNodeDocument(
            u'a:' + actionType.label,
            actionType.namespace,
            attributes = attributes,
            prefixes={
                u'a' : actionType.namespace,
            }
        )
        
        return doc
    
    
    def createBody(self, context, node, locale):
        nxa = node.xml_append
        nxc = node.xml_create_element
        
        self.createHead(
            context,
            nxa(
                nxc(
                    u'a:head', MYELINS
                )
            ),
            locale
        )
                
        self.createContent(
            context,
            nxa(
                nxc(
                    u'a:content', MYELINS,
                    attributes = {
                        (u'xml:lang',XML_NS): locale,
                    }
                )
            ),
            locale
        )
        
        return node
    
    def createHead(self, context, node, locale):
        nxa = node.xml_append
        nxc = node.xml_create_element
        
        nxa(
            nxc(
                u'a:title', MYELINS,
                attributes={
                    u'key' : unicode(context.action),
                    (u'xml:lang',XML_NS): locale,
                },
                content=context.model.rdf_join('dcTitle')
            )
        )
        
        self.createAccount(
            context,
            nxa(
                nxc(
                    u'a:account', MYELINS
                )
            ),
            locale
        )
        
        self.createModes(
            context,
            nxa(
                nxc(
                    u'a:modes', MYELINS
                )
            )
        )
        
        self.createMethods(
            context,
            nxa(
                nxc(
                    u'a:methods', MYELINS
                )
            )
        )
                
        self.createMeta(
            context,
            nxa(
                nxc(
                    u'a:meta', MYELINS,
                    attributes = {
                        (u'xml:lang',XML_NS) : locale,
                    }
                )
            ),
            locale
        )
        
        self.createNav(
            context,
            nxa(
                nxc(
                    u'a:nav', MYELINS
                )
            ),
            locale
        )
    
    
    def createAccount(self, context, node, locale):
        if context.account.isAgent():
            self.newAgentAccount().createAccount(context, node, locale)
        else:
            self.newGuestAccount().createAccount(context, node, locale)
        return node
    
    def createModes(self, context, node):
        return node
    
    def createMethods(self, context, node):    
        curMethod = context.method
        keys = context.methods.keys()
        if keys:
            nxa = node.xml_append
            nxc = node.xml_create_element
            
            map = self.extensionsMap.get
            #baseUrl = context.resourceUri
            #url = context.urlFormatter.formatUrl
            keys.sort()
            if keys[0] == '':                
                nxa(
                    nxc(
                        u'a:method', MYELINS,
                        attributes={
                            u'key'      : u'',
                            u'imt'      : context.model.rdf_join('dcFormat'),
                            #u'href'     : url(baseUrl,method=None),
                        }
                    )
                )
                keys = keys[1:]
                
            for m in keys:
                t = map(m)
                if not t:
                    continue
                if m == curMethod:
                    nxa(
                        nxc(
                            u'a:method', MYELINS,
                            attributes={
                                u'key'      : unicode(m),
                                u'imt'      : t.imt,
                                u'selected' : u'1',
                                #u'href'     : url(baseUrl, method=m)
                            }
                        )
                    )
                else:
                    nxa(
                        nxc(
                            u'a:method', MYELINS,
                            attributes={
                                u'key'      : unicode(m),                                
                                u'imt'      : t.imt,
                                #u'href'     : url(baseUrl, method=m)
                            }
                        )
                    )
                    
        return node
        
    #def createHeader(self, context, node, locale):
    #    node.xml_append(
    #        node.xml_create_element(
    #            u'a:title', MYELINS,
    #            attributes={
    #                u'key' : unicode(context.action),
    #            },
    #            content=context.model.rdf_join('dcTitle')
    #        )
    #    )
    #    return node
        
    def createNav(self, context, node, locale):
        return node
    
    def createMeta(self, context, node, locale):
        return node
    
    def createContent(self, context, node, locale):
        return node
    
    
# cleanup
del amara, \
    Account, \
    ModelDriver